<template>
  <div class="login-page">
    <van-nav-bar
      title="登录/注册"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="page-container">
      <div class="login-logo">
        <img src="../assets/logo.png" alt="数独游戏" />
      </div>
      
      <van-tabs v-model:active="activeTab">
        <van-tab title="登录">
          <van-form @submit="onSubmitLogin">
            <van-cell-group inset>
              <van-field
                v-model="loginForm.username"
                name="username"
                label="用户名"
                placeholder="请输入用户名"
                :rules="[{ required: true, message: '请填写用户名' }]"
              />
              <van-field
                v-model="loginForm.password"
                type="password"
                name="password"
                label="密码"
                placeholder="请输入密码"
                :rules="[{ required: true, message: '请填写密码' }]"
              />
            </van-cell-group>
            
            <div style="margin: 16px;">
              <van-button round block type="primary" native-type="submit">
                登录
              </van-button>
            </div>
          </van-form>
        </van-tab>
        
        <van-tab title="注册">
          <van-form @submit="onSubmitRegister">
            <van-cell-group inset>
              <van-field
                v-model="registerForm.username"
                name="username"
                label="用户名"
                placeholder="请输入用户名"
                :rules="[{ required: true, message: '请填写用户名' }]"
              />
              <van-field
                v-model="registerForm.password"
                type="password"
                name="password"
                label="密码"
                placeholder="请输入密码"
                :rules="[
                  { required: true, message: '请填写密码' },
                  { min: 6, message: '密码长度不能少于6位' }
                ]"
              />
              <van-field
                v-model="registerForm.confirmPassword"
                type="password"
                name="confirmPassword"
                label="确认密码"
                placeholder="请再次输入密码"
                :rules="[
                  { required: true, message: '请再次输入密码' },
                  { validator: validateConfirmPassword, message: '两次输入的密码不一致' }
                ]"
              />
            </van-cell-group>
            
            <div style="margin: 16px;">
              <van-button round block type="primary" native-type="submit">
                注册
              </van-button>
            </div>
          </van-form>
        </van-tab>
      </van-tabs>
      
      <div class="wechat-login-section" v-if="isInWechat">
        <div class="divider">
          <span>或</span>
        </div>
        
        <van-button 
          round 
          block 
          color="#07c160"
          icon="wechat"
          @click="wechatLogin"
        >
          微信登录
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '../store/user';
import { showToast, showLoadingToast, showSuccessToast, showFailToast } from 'vant';
import WechatUtil from '../utils/wechat';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const activeTab = ref(0);
const isInWechat = ref(WechatUtil.isWechatBrowser());

// 登录表单
const loginForm = ref({
  username: '',
  password: ''
});

// 注册表单
const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: ''
});

// 验证确认密码
const validateConfirmPassword = (val) => {
  if (val === registerForm.value.password) {
    return true;
  }
  return false;
};

// 提交登录表单
const onSubmitLogin = async () => {
  Toast.loading({
    message: '登录中...',
    forbidClick: true,
  });
  
  try {
    const result = await userStore.userLogin({
      username: loginForm.value.username,
      password: loginForm.value.password
    });
    
    if (result) {
      showSuccessToast('登录成功');
      
      // 如果有重定向参数，跳转到指定页面
      if (route.query.redirect) {
        router.replace(route.query.redirect);
      } else {
        router.replace('/');
      }
    } else {
      showFailToast('用户名或密码错误');
    }
  } catch (error) {
    console.error('登录错误', error);
    showFailToast('登录失败，请重试');
  }
};

// 提交注册表单
const onSubmitRegister = async () => {
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    showToast('两次输入的密码不一致');
    return;
  }
  
  showLoadingToast({
    message: '注册中...',
    forbidClick: true,
  });
  
  try {
    const result = await userStore.userRegister({
      username: registerForm.value.username,
      password: registerForm.value.password
    });
    
    if (result) {
      showSuccessToast('注册成功');
      
      // 自动登录
      await userStore.userLogin({
        username: registerForm.value.username,
        password: registerForm.value.password
      });
      
      // 如果有重定向参数，跳转到指定页面
      if (route.query.redirect) {
        router.replace(route.query.redirect);
      } else {
        router.replace('/');
      }
    } else {
      showFailToast('注册失败，用户名可能已存在');
    }
  } catch (error) {
    console.error('注册错误', error);
    showFailToast('注册失败，请重试');
  }
};

// 微信登录
const wechatLogin = () => {
  if (WechatUtil.isWechatBrowser()) {
    // 获取当前页面的完整URL，包括重定向参数
    const currentUrl = window.location.href;
    const redirectUri = route.query.redirect 
      ? `${window.location.origin}/login?redirect=${encodeURIComponent(route.query.redirect)}`
      : currentUrl;
    
    // 跳转到微信授权页面
    WechatUtil.getAuthCode(redirectUri);
  } else {
    showToast('请在微信中打开以使用微信登录');
  }
};

// 处理从微信重定向回来的情况
const handleWechatCallback = async () => {
  // 从URL中获取code参数
  const code = WechatUtil.getCodeFromUrl();
  
  if (code) {
    showLoadingToast({
      message: '登录中...',
      forbidClick: true,
    });
    
    try {
      const result = await userStore.wechatLogin(code);
      
      if (result) {
        showSuccessToast('登录成功');
        
        // 清除URL中的code参数
        const redirectUrl = window.location.href.split('?')[0];
        window.history.replaceState({}, document.title, redirectUrl);
        
        // 如果有重定向参数，跳转到指定页面
        if (route.query.redirect) {
          router.replace(route.query.redirect);
        } else {
          router.replace('/');
        }
      } else {
        showFailToast('微信登录失败');
      }
    } catch (error) {
      console.error('微信登录错误', error);
      showFailToast('微信登录失败，请重试');
    }
  }
};

// 返回按钮点击事件
const onClickLeft = () => {
  router.back();
};

// 在组件挂载时检查是否是微信回调
onMounted(() => {
  handleWechatCallback();
});
</script>

<style scoped>
.login-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.login-logo {
  text-align: center;
  margin: 30px 0;
}

.login-logo img {
  width: 80px;
  height: 80px;
}

.wechat-login-section {
  margin-top: 30px;
}

.divider {
  position: relative;
  text-align: center;
  margin: 20px 0;
}

.divider::before,
.divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 40%;
  height: 1px;
  background-color: #dcdee0;
}

.divider::before {
  left: 0;
}

.divider::after {
  right: 0;
}

.divider span {
  display: inline-block;
  padding: 0 10px;
  background-color: #f7f8fa;
  position: relative;
  z-index: 1;
  color: #969799;
}
</style>
